//
//  MoneyTextField.m
//  SSJC
//
//  Created by xzm on 16/12/5.
//  Copyright © 2016年 admin. All rights reserved.
//

#import "MoneyTextField.h"

#define myDotNumbers     @"0123456789.\n"
#define myNumbers          @"0123456789\n"
#define DecimalPointFrondNumber 8 //小数点前
#define DecimalPointBehindNumber 2 //小数点后


@implementation MoneyTextField

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    
    if (self) {
        self.delegate = self;
        self.keyboardType = UIKeyboardTypeDecimalPad;
    }
    
    return self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([string isEqualToString:@"\n"]||[string isEqualToString:@""]) {//按下return
        return YES;
    }
    
    
    NSCharacterSet *cs;
    NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
    if (NSNotFound == nDotLoc && 0 != range.location) { //无小数点的情况
        cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers]invertedSet];
        if ([string isEqualToString:@"."]) {
            return YES;
        }
        if (textField.text.length>=DecimalPointFrondNumber) {  //小数点前面的位数
            return NO;
        }
    }
    else { //有小数点的情况
        cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers]invertedSet];
        if (textField.text.length>=DecimalPointFrondNumber+DecimalPointBehindNumber+1 || [string isEqualToString:@"."]) {
            return  NO;
        }

    }
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    if (!basicTest) {
        return NO;
    }
    if (NSNotFound != nDotLoc && range.location > nDotLoc +DecimalPointBehindNumber) {//小数点后面两位
        return NO;
    }
    return YES;
}

@end
